package mo.tags.stack;

import java.util.Arrays;
import java.util.Stack;

public class LO2_37 {

    public int[] asteroidCollision(int[] asteroids) {
        Stack<Integer> stack = new Stack<>();
        for (int e : asteroids) {
            if (e > 0) {
                stack.push(e);
            } else {
                if (stack.isEmpty() || stack.peek() < 0) {
                    stack.push(e);
                    continue;
                }
                boolean needAdd = true;
                while (!stack.isEmpty() && stack.peek() > 0) {
                    if (stack.peek() < -e) {
                        stack.pop();
                    } else {
                        if (stack.peek() == -e) {
                            stack.pop();
                        }
                        needAdd = false;
                        break;
                    }
                }
                if (needAdd) {
                    stack.push(e);
                }
            }
        }
        int size = stack.size();
        int[] res = new int[size];
        for (int i = 0; i < size; i++) {
            res[size-1-i] = stack.pop();
        }
        return res;
    }

    public static void main(String[] args) {
        LO2_37 test = new LO2_37();
        System.out.println(Arrays.toString(test.asteroidCollision(new int[]{5, 10, -5})));
    }
}
